﻿<%@ WebHandler Language="C#" Class="ErpSendMESMaterialVue3PageHandler" %>

/* Description:配套单校准
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.10.21
 */

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Collections;
using System.IO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using BusinessRule.DTO;
using System.Configuration;

public class ErpSendMESMaterialVue3PageHandler : IHttpHandler, IRequiresSessionState
{
    class Result
    {
        public object data { get; set; }
        public Meta meta { get; set; }
        public int total { get; set; }
        public class Meta
        {
            public int status;
            public string msg;
            public Meta(int status, string msg)
            {
                this.status = status;
                this.msg = msg;
            }
        }
    }

    BusinessRule.IBusiness.uLMSCommonIBusiness m_Common = BusinessRule.BusinessFactory.uMESBusinessFactory.instance.GetuLMSCommonObject();
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getUserInfo":
                        r = getUserInfo();//查询当前用户信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getMfgorderData":
                        r = getMfgorderData(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getBom":
                        r = getBom(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getErp":
                        r = getErp(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDiff":
                        r = getDiff(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "resendErp":
                        r = resendErp(jObject);//重推
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getUserInfo()
    {
        Result r = new Result();
        r.data = m_UserInfo;
        r.total = 0;
        r.meta = m_UserInfo == null ? new Result.Meta(500, "当前未登录") : new Result.Meta(200, "请求成功");
        return r;
    }

    Result getMfgorderData(JObject jObject)
    {
        string sql = @"
SELECT DISTINCT mfg.mfgorderid,mfg.mfgordername,mfg.qty,mfg.plannedstartdate,pb3.productname,
       mfg.plannedcompletiondate
FROM mfgorder mfg
--查订单件号信息
LEFT JOIN productbase pb2 ON pb2.productbaseid = mfg.productbaseid
LEFT JOIN product p2 ON p2.productid = NVL(pb2.revofrcdid,mfg.productid)
LEFT JOIN productbase pb3 ON pb3.productbaseid=p2.productbaseid
--查件号默认工艺信息
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = p2.workflowbaseid
LEFT JOIN workflow wf ON wf.workflowid = NVL(wfb.revofrcdid,p2.workflowid)
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN orderstatus od ON mfg.orderstatusid = od.orderstatusid
WHERE NVL(od.orderstatusname,'打开') <> '关闭'";
        //件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND pb3.productname LIKE '%{0}%'", jObject["productname"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername LIKE '%{0}%'", jObject["mfgordername"].ToString());
        }

        //主制分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND mfg.factoryid = '{0}'", jObject["factoryid"].ToString());
        }

        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(jObject["currentPage"]);//页码
        paraPage.PageSize = Convert.ToInt32(jObject["pageSize"]);//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        DataTable dtResult = result.DBTable;

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(result.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getBom(JObject jObject)
    {
        string sql = @"
SELECT mfg.mfgorderid,mfg.mfgordername,mfg.qty,mfg.plannedstartdate,pb3.productname mfgproductname,
       mfg.plannedcompletiondate,sb2.specname,s.specno,s.opdesc,pbn.productname,pml.qtyrequired,
       b.bomid,bb.bomname,pml.productmateriallistitemid,pml.productid,pml.qtyrequired * mfg.qty mesqty
FROM mfgorder mfg
--查订单件号信息
LEFT JOIN productbase pb2 ON pb2.productbaseid = mfg.productbaseid
LEFT JOIN product p2 ON p2.productid = NVL(pb2.revofrcdid,mfg.productid)
LEFT JOIN productbase pb3 ON pb3.productbaseid=p2.productbaseid
--查件号默认工艺信息
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = p2.workflowbaseid
LEFT JOIN workflow wf ON wf.workflowid = NVL(wfb.revofrcdid,p2.workflowid)
--bom信息
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
--bom工序信息
LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
LEFT JOIN spec s ON  s.specid=NVL(sb.revofrcdid, pml.specid)
LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
--子零件信息
LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
WHERE mfg.mfgordername = '{0}'
ORDER BY s.specno";
        sql = string.Format(sql, jObject["mfgordername"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtBom;
        r.total = Convert.ToInt32(dtBom.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getErp(JObject jObject)
    {
        string sql = @"SELECT * FROM erp_send_material erp WHERE erp.mfgordername = '{0}'";
        sql = string.Format(sql, jObject["mfgordername"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtBom;
        r.total = Convert.ToInt32(dtBom.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getDiff(JObject jObject)
    {
        string mfgordername = jObject["mfgordername"].ToString();
        string sql = @"
SELECT t.id,t.specno,t.specname,t.productname,t.diffqty,t.mfgordername,
       DECODE(t.oper_type,1,'增加数量',2,'减少数量',3,'增加条目',4,'删除条目') oper_type,
       t.oper_type oper_type2,
       t.erp_return_date,t.createdate,'已推送' send_status,
       DECODE(t.erp_status,0,'失败',1,'成功') erp_status,t.erp_msg
FROM erp_mes_bom_diff t
WHERE t.mfgordername = '{0}' AND t.diff_type = 'ERP'";
        sql = string.Format(sql, mfgordername);
        DataTable dtDiff = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtDiff.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtDiff;
        r.total = Convert.ToInt32(dtDiff.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result resendErp(JObject jObject)
    {
        Result r = new Result();
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(jObject["postData"].ToString());
        string mfgordername = "";
        if (dtPostData.Rows.Count > 0)
        {
            mfgordername = dtPostData.Rows[0]["mfgordername"].ToString();
            string insertSql = string.Format("INSERT INTO mes_send_erp_diff(mfgordername,diff_type) VALUES('{0}','ERP')", mfgordername);
            int count = DatabaseHelper.ExecuteSql(insertSql);
            r.data = count > 0;
            r.total = 0;
            r.meta = new Result.Meta(200, "请求成功");
            return r;
        }
        r.data = false;
        r.total = 0;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}